//
//  wxAppDelegate.m
//  lvtu
//
//  Created by Shi Zijie on 12-3-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "wxAppDelegate.h"
#import "BaseViewController.h"
#import "NetDataSource.h"
#import "LoginViewController.h"
#import "RecommondViewController.h"
#import "UserCenterViewController.h"
#import "DateDesignViewController.h"
#import "SettingViewController.h"
#import "CommentViewController.h"
#import "testViewController.h"
#import "DataSource.h"
#import "StartViewController.h"
#import "MobClick.h"

@implementation wxAppDelegate

@synthesize window = _window;
@synthesize navigationController = _navigationController;
@synthesize loginInfo;
@synthesize isLogin;

- (void)dealloc
{
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    [[DataSource shareInstance] initData];
    //[self launchFirstView];
    self.loginInfo = [[DataSource shareInstance] getUserStatsFromKeyChain];
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.backgroundColor = [UIColor blackColor];//[UIColor whiteColor];
    
    StartViewController* viewController = [[StartViewController alloc] init];
    _navigationController = [[UINavigationController alloc]initWithRootViewController:viewController];
    [viewController release];
    [_navigationController setNavigationBarHidden:YES animated:NO];
    
    [self.window addSubview:[_navigationController view]];
    [self.window makeKeyAndVisible];
    isLogin = NO;
    
    if (loginInfo.email && ![loginInfo.email isEqualToString:@""]) {
        NSString* psword = [[DataSource shareInstance] md5_hexDigest:loginInfo.password];
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:loginInfo.email/*@"martin.szj@gmail.com"*/,@"email",psword/*@"123456"*/,@"password",
                              [[DataSource shareInstance] sys_getOSVersion],@"os",
                              LVTU_CLIENT_VERSION,@"version",
                              LVTU_CHANNEL,@"channel",
                              [[DataSource shareInstance] sys_getDeviceModelName],@"device_name",
                              [[DataSource shareInstance] sys_getDeviceID],@"device_id",
                              @"1",@"is_iphone",
                              nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = LOGININFO;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_o_login" postInfo:info userInfo:msg];
        [info release];
    }
    else {
//        [self launchFirstView];
        [self showTabMainFrame];
    }
//    testViewController* test = [[testViewController alloc] init];
//    self.window.rootViewController = test;

    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 50000
    NSString *devicetype =[UIDevice currentDevice].systemVersion;
	if ([devicetype floatValue] >= 5.0)
	{
        [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"bg_title.png"] forBarMetrics:UIBarMetricsDefault];
	}
#endif
    
    [MobClick startWithAppkey:@"501e11565270154c68000004" reportPolicy:REALTIME channelId:LVTU_CHANNEL];
    [MobClick checkUpdate];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}
+ (wxAppDelegate*) getAppDelegate
{
	return (wxAppDelegate*)[UIApplication sharedApplication].delegate;
}

-(void)popAllViewController
{
    if (_navigationController != nil)
	{
        int cnt = [[wxAppDelegate getAppDelegate].navigationController.viewControllers count];
        for (int index = 0; index < cnt; index++) {
            [self.navigationController popViewControllerAnimated:NO];
        }
		[_navigationController.view removeFromSuperview];
        [_navigationController release];
        _navigationController = nil;
	}
}

-(void)enterMytripView
{
    UINavigationController* designNavigationController = [[_tabBarController viewControllers] objectAtIndex:2];
    if ( designNavigationController != nil) {
        int cnt = [designNavigationController.viewControllers count];
        for (int index = 0; index < cnt-1; index++) {
            [[DataSource shareInstance] resetData];
            [designNavigationController popViewControllerAnimated:NO];
        }
    }
    _tabBarController.selectedIndex = 1;
#ifdef CustomTabBar
    [_tabBarController selectedTab:[_tabBarController.buttons objectAtIndex:1]];
#endif
    
    UINavigationController* userNavigationController = [[_tabBarController viewControllers] objectAtIndex:1];
    if ( userNavigationController != nil) {
        int cnt = [userNavigationController.viewControllers count];
        for (int index = 0; index < cnt-1; index++) {
            [userNavigationController popViewControllerAnimated:NO];
        }
        UserCenterViewController* userViewController = [[userNavigationController viewControllers] objectAtIndex:0];
        [userViewController setSegmentedControlEventValue:0];
    }
}

- (void) launchFirstView
{
    isLogin = NO;
    LoginViewController * viewController = [[LoginViewController alloc] init];
    _navigationController = [[UINavigationController alloc]initWithRootViewController:viewController];
    viewController.navigationController.navigationBarHidden = YES;
    [self.window addSubview:_navigationController.view];
    [viewController release];
    
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = CITYLIST;
    msg.ui_delegate = self;
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_city_list" postInfo:nil userInfo:msg];
}

- (void) showTabMainFrame
{
    if ( _tabBarController == nil )
    {
        _tabBarController = [[CustomTabBarController alloc] init];
#ifdef CustomTabBar
        _tabBarController.tabBar.hidden = YES;
        _tabBarController.customTabBarDelegate = self;
#endif
        NSMutableArray * tabArray = [NSMutableArray arrayWithCapacity:5];
        
        UINavigationController * _tempNavController = nil;
        
        // 推荐 
        RecommondViewController * recommondViewController = [[RecommondViewController alloc] init];
        _tempNavController = [[UINavigationController alloc] initWithRootViewController:recommondViewController];
        _tempNavController.tabBarItem.image = [UIImage imageNamed:@"btn_main01_normal.png"];
        [tabArray addObject:_tempNavController];
        [_tempNavController release];_tempNavController = nil;
        [recommondViewController release];
        
        // 用户中心 
        UserCenterViewController * userCenterViewController = [[UserCenterViewController alloc] init];
        _tempNavController = [[UINavigationController alloc] initWithRootViewController:userCenterViewController];
        _tempNavController.tabBarItem.image = [UIImage imageNamed:@"btn_main02_normal.png"];
        [tabArray addObject:_tempNavController];
        [_tempNavController release];_tempNavController = nil;
        [userCenterViewController release];
        
        // 旅途设计
        DateDesignViewController * designViewController = [[DateDesignViewController alloc] init];
        _tempNavController = [[UINavigationController alloc] initWithRootViewController:designViewController];
        _tempNavController.tabBarItem.image = [UIImage imageNamed:@"btn_main03_normal.png"];
        [tabArray addObject:_tempNavController];
        [_tempNavController release];_tempNavController = nil;
        [designViewController release];
        
        // 评论 
        CommentViewController * commentViewController = [[CommentViewController alloc] init];
        _tempNavController = [[UINavigationController alloc] initWithRootViewController:commentViewController];
        _tempNavController.tabBarItem.image = [UIImage imageNamed:@"btn_main04_normal.png"];
        [tabArray addObject:_tempNavController];
        [_tempNavController release];_tempNavController = nil;
        [commentViewController release];
        
        // 设置
        SettingViewController * settingViewController = [[SettingViewController alloc] init];
        _tempNavController = [[UINavigationController alloc] initWithRootViewController:settingViewController];
        _tempNavController.tabBarItem.image = [UIImage imageNamed:@"btn_main05_normal.png"];
        [tabArray addObject:_tempNavController];
        [_tempNavController release];_tempNavController = nil;
        [settingViewController release];
        
        [_tabBarController setViewControllers:tabArray animated:NO];
    }
	
	// made 动态 first view
    
    if (isLogin) {
        _tabBarController.selectedIndex = 0;
#ifdef CustomTabBar
        [_tabBarController selectedTab:[_tabBarController.buttons objectAtIndex:0]];
#endif
    }
    else
    {
        _tabBarController.selectedIndex = 0;
#ifdef CustomTabBar
        [_tabBarController selectedTab:[_tabBarController.buttons objectAtIndex:0]];

#endif
    }
    [self.window addSubview:_tabBarController.view];
    
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = CITYLIST;
    msg.ui_delegate = self;
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_city_list_new" postInfo:nil userInfo:msg];
}

#pragma mark - tab bar
#ifdef CustomTabBar
- (void)selectedItemImagesForTabBar:(CustomTabBarController*) tabView buttons:(NSMutableArray*)tabButtons
{
    UIButton * button0 = [tabView.buttons objectAtIndex:0];
    [button0 setImage:[UIImage imageNamed:@"btn_main01_press.png"] forState:UIControlStateSelected];
    
    UIButton * button1 = [tabButtons objectAtIndex:1];
    [button1 setImage:[UIImage imageNamed:@"btn_main02_press.png"] forState:UIControlStateSelected];
    
    UIButton * button2 = [tabButtons objectAtIndex:2];
    [button2 setImage:[UIImage imageNamed:@"btn_main03_press.png"] forState:UIControlStateSelected];
    
    UIButton * button3 = [tabButtons objectAtIndex:3];
    [button3 setImage:[UIImage imageNamed:@"btn_main04_press.png"] forState:UIControlStateSelected];
    
    UIButton * button4 = [tabButtons objectAtIndex:4];
    [button4 setImage:[UIImage imageNamed:@"btn_main05_press.png"] forState:UIControlStateSelected];
}
- (UIColor*) backgroundColorForTabBar:(CustomTabBarController*) tabView
{
    //return [UIColor colorWithRed:0.0 green:115.0/255 blue:232.0/255 alpha:1.0];
    return [UIColor blackColor];
}

- (UIColor*) selectedTitleColor:(CustomTabBarController*)tabView
{
    return [UIColor blackColor];
}
- (UIColor*) normalTitleColor:(CustomTabBarController*)tabView
{
    return [UIColor colorWithRed:0.0/255 green:58.0/255 blue:121.0/255 alpha:1.0];
}

-(void)customTabBarDidSelectItem
{
    if (isLogin == NO) {
        [self popAllViewController];
        [self launchFirstView];
    }
}

#endif

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: LOGININFO]) {
        isLogin = YES;
        [[DataSource shareInstance] saveUserStatusToKeyChain:loginInfo.email passwd:loginInfo.password];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = PERSONINFO;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance] postTo:@"http://www.wxlvtu.com/?a=page_personal_information" postInfo:nil userInfo:msg];
        
        //登录成功，进入主页面
        [[wxAppDelegate getAppDelegate] showTabMainFrame];
    }
    else if ([coreMsg.data isEqual: PERSONINFO])
    {
        if ([data isKindOfClass:[UserInfo class]]) {
            [DataSource shareInstance].userInfo = (UserInfo*)data;
        }
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: LOGININFO]) {
        [self launchFirstView];
    }
}
@end
